<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属地区" prop="regionId">
        <el-select v-model="queryParams.regionId" placeholder="请选择地区" clearable>
          <el-option
            v-for="region in regionList"
            :key="region.id"
            :label="region.name"
            :value="region.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属级别" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择所属级别" clearable>
          <el-option label="国家级" value="国家级" />
          <el-option label="省级" value="省级" />
          <el-option label="市级" value="市级" />
          <el-option label="县级" value="县级" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in ich_item_status"
            :key="dict.value"
            :label="dict.label"
            :value="Number(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['management:item:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['management:item:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['management:item:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['management:item:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="所属分类" align="center" prop="categoryId">
      <template #default="scope">
      <span>{{ categoryNameById[scope.row.categoryId] || scope.row.categoryName || scope.row.categoryId }}</span>
      </template>
      </el-table-column>
      <el-table-column label="所属地区" align="center" prop="regionId">
      <template #default="scope">
      <span>{{ regionNameById[scope.row.regionId] || scope.row.regionName || scope.row.regionId }}</span>
      </template>
      </el-table-column>
      <el-table-column label="所属级别" align="center" prop="level" />
      <el-table-column label="项目简介" align="center" prop="introduction">
        <template #default="scope">
          <el-tooltip effect="dark" placement="top" :content="scope.row.introduction">
            <div class="clamp-2">{{ scope.row.introduction }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="详细内容" align="center" width="100">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleViewDetail(scope.row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="statusText">
        <template #default="scope">
          <el-tag :type="(Number(scope.row.status) === 1 || scope.row.statusText === '启用') ? 'success' : 'info'">
            {{ (Number(scope.row.status) === 1 || scope.row.statusText === '启用') ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['management:item:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['management:item:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="itemRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入项目名称" />
            </el-form-item>
            <el-form-item label="所属分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择所属分类" style="width: 100%">
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属地区" prop="regionId">
              <el-select v-model="form.regionId" placeholder="请选择所属地区" style="width: 100%">
                <el-option
                  v-for="region in regionList"
                  :key="region.id"
                  :label="region.name"
                  :value="region.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属级别" prop="level">
              <el-select v-model="form.level" placeholder="请选择所属级别">
                <el-option label="国家级" value="国家级" />
                <el-option label="省级" value="省级" />
                <el-option label="市级" value="市级" />
                <el-option label="县级" value="县级" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目简介" prop="introduction">
              <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="封面图片" prop="imageUrl">
              <image-upload v-model="form.imageUrl" :limit="1" :key="dialogKey"/>
            </el-form-item>
            <el-form-item label="状态" prop="status" v-if="form.id">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 详情内容标签页 -->
        <el-tab-pane label="详情内容" name="detail">
          <el-form ref="detailRef" :model="detailForm" label-width="80px">
            <el-form-item label="详细介绍">
              <WangEditor 
                v-model="detailForm.description" 
                :height="300" 
                placeholder="请输入详细介绍内容"
                :key="`editor-${detailDialogKey}`"
                ref="editorRef"
              />
            </el-form-item>
            <el-form-item label="相关图片">
              <image-upload 
                v-model="detailForm.images" 
                :limit="10" 
                :multiple="true"
                :key="detailDialogKey"
                list-type="picture-card"
              />
              <div class="form-tip">支持上传多张图片，最多10张</div>
            </el-form-item>
            <el-form-item label="相关视频">
              <file-upload 
                v-model="detailForm.videos" 
                :limit="5"
                :multiple="true"
                :file-type="['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm']"
                :key="detailDialogKey"
              />
              <div class="form-tip">支持上传多个视频文件，最多5个，支持格式：mp4、avi、mov、wmv、flv、webm</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Item">
import { listItem, getItem, delItem, addItem, updateItem, getItemCategories, getItemRegions, getItemDetail } from "@/api/management/item"
import { useRouter } from 'vue-router'
import WangEditor from '@/components/WangEditor/index.vue'
import { useDict } from '@/utils/dict'

const { proxy } = getCurrentInstance()
const router = useRouter()
const { ich_item_status } = useDict('ich_item_status')

const itemList = ref([])
const categoryList = ref([])
const regionList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dialogKey = ref(0)  // 用于强制重新渲染ImageUpload组件
const detailDialogKey = ref(0)  // 用于强制重新渲染详情组件
const activeTab = ref('basic')  // 当前激活的标签页

// 详情表单数据
const detailForm = ref({
  description: '',
  images: [],
  videos: []
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryId: null,
    regionId: null,
    level: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "项目名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "所属不能为空", trigger: "blur" }
    ],
    regionId: [
      { required: true, message: "所属地区不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "所属级别不能为空", trigger: "blur" }
    ],
    introduction: [
      { required: true, message: "项目简介不能为空", trigger: "blur" }
    ],
    imageUrl: [
      { required: true, message: "封面图片不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询项目管理列表 */
function getList() {
  loading.value = true
  const params = {
    ...queryParams.value,
    status: queryParams.value.status == null ? null : Number(queryParams.value.status)
  }
  listItem(params).then(response => {
    // 按照ID从小到大排序
    itemList.value = response.rows.sort((a, b) => a.id - b.id)
    total.value = response.total
    loading.value = false
  })
}

/** 获取分类列表 */
function getCategoryList() {
  getItemCategories().then(response => {
    categoryList.value = response.data
  })
}

/** 获取地区列表 */
function getRegionList() {
  getItemRegions().then(response => {
    regionList.value = response.data
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    categoryId: null,
    regionId: null,
    level: null,
    introduction: null,
    imageUrl: "",  // 改为空字符串而不是null
    status: null,
    createdAt: null,
    updatedAt: null
  }
  // 重置详情表单 - 使用nextTick确保安全更新
  nextTick(() => {
    detailForm.value = {
      description: '',
      images: [],
      videos: []
    }
  })
  // 重置到基本信息标签页
  activeTab.value = 'basic'
  proxy.resetForm("itemRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialogKey.value++  // 强制重新渲染ImageUpload组件
  detailDialogKey.value++  // 强制重新渲染详情组件
  // 确保在下一个事件循环中打开对话框，让重置完全生效
  nextTick(() => {
    open.value = true
    title.value = "添加项目"
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('handleUpdate called with row:', row)
  reset()
  dialogKey.value++  // 强制重新渲染ImageUpload组件
  detailDialogKey.value++  // 强制重新渲染详情组件和编辑器
  const _id = row.id || ids.value
  console.log('Getting item detail for id:', _id)
  
  // 调用详情接口获取完整数据（包含基本信息和详情信息）
  getItemDetail(_id).then(response => {
    console.log('getItemDetail response:', response)
    const data = response.data
    
    // 填充基本信息表单 - 使用扁平化的数据结构
    form.value = {
      id: data.id,
      name: data.name,
      categoryId: data.categoryId,
      regionId: data.regionId,
      level: data.level,
      introduction: data.introduction,
      imageUrl: data.imageUrl,
      status: Number(data.status)
    }
    
    // 填充详情表单 - 直接从扁平化数据中获取详情字段
    detailForm.value = {
      description: data.description || '',
      images: data.images ? (typeof data.images === 'string' ? 
        (() => {
          try {
            return JSON.parse(data.images)
          } catch (e) {
            // 如果解析失败，按照旧格式处理
            return data.images.split(',').map(url => url.trim()).filter(url => url)
          }
        })() : data.images) : [],
      videos: data.videos ? (typeof data.videos === 'string' ? 
        (() => {
          try {
            return JSON.parse(data.videos)
          } catch (e) {
            // 如果解析失败，按照旧格式处理
            return data.videos.split(',').map(url => url.trim()).filter(url => url)
          }
        })() : data.videos) : []
    }
    
    // 确保在下一个事件循环中打开对话框
    nextTick(() => {
      console.log('Opening dialog with title: 修改项目')
      open.value = true
      title.value = "修改项目"
      
      // 重置编辑器内容，确保清除残留数据
      nextTick(() => {
        // 直接设置内容，让编辑器的watch机制处理重新渲染
        detailForm.value.description = data.description || ''
        console.log('Set description:', data.description)
      })
    })
  }).catch(error => {
    console.error('获取项目详情失败:', error)
    proxy.$modal.msgError("获取项目详情失败: " + (error.message || error))
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["itemRef"].validate(valid => {
    if (valid) {
      // 准备提交数据，包含基本信息和详情信息
      const submitData = {
        ...form.value,
        itemDetail: {
          description: detailForm.value.description,
          images: Array.isArray(detailForm.value.images) ? JSON.stringify(detailForm.value.images) : detailForm.value.images,
          videos: Array.isArray(detailForm.value.videos) ? JSON.stringify(detailForm.value.videos) : detailForm.value.videos
        }
      }
      
      if (form.value.id != null) {
        updateItem(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          // 关闭弹窗并刷新列表，重置编辑器key避免残留
          detailDialogKey.value++
          getList()
        })
      } else {
        // 新增时不提交状态字段，保持数据库默认启用
        delete submitData.status
        addItem(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 计算页面序号
  let displayNumbers = []
  
  // 如果有批量选中的项目，优先显示所有选中项目的序号
  if (ids.value && ids.value.length > 0) {
    // 批量删除或有选中项时：显示所有选中项的序号
    ids.value.forEach(id => {
      const index = itemList.value.findIndex(item => item.id === id)
      if (index !== -1) {
        const pageNumber = (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1
        displayNumbers.push(pageNumber)
      }
    })
  } else if (row) {
    // 单个删除且没有选中项：只显示当前行的序号
    const index = itemList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      const pageNumber = (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1
      displayNumbers.push(pageNumber)
    }
  }
  
  const _ids = (ids.value && ids.value.length > 0) ? ids.value : (row ? row.id : [])
  const displayText = displayNumbers.length > 1 
    ? displayNumbers.join('、') 
    : displayNumbers[0] || _ids
    
  proxy.$modal.confirm('是否确认删除项目序号为"' + displayText + '"的数据项？').then(function() {
    return delItem(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('management/item/export', {
    ...queryParams.value
  }, `item_${new Date().getTime()}.xlsx`)
}

/** 查看详情按钮操作 */
function handleViewDetail(row) {
  router.push({
    path: '/management/item-detail/index',
    query: { id: row.id }
  })
}

const categoryNameById = computed(() => Object.fromEntries((categoryList.value || []).map(c => [c.id, c.name])))
const regionNameById = computed(() => Object.fromEntries((regionList.value || []).map(r => [r.id, r.name])))
getList()
getCategoryList()
getRegionList()
</script>

<style scoped>
.clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}
</style>
